<?php

namespace app\admin\controller\depot;

use app\common\controller\Backend;

// 退货管理
class Back extends Backend
{
    protected $model = null;

    protected $relationSearch = false;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Depot.Back.Back');
        $this->BackProductModel = model('Depot.Back.Product');
        $this->view->assign("statuslist", $this->model->statuslist());
        $this->assignconfig('statuslist', $this->model->statuslist());
    }

    // 列表
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()) 
        {
            if ($this->request->request('keyField')) 
            {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->with(['business'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();

            $list = $this->model
                ->with(['business'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    // 添加退货
    public function add()
    {
        if($this->request->isPost())
        {
            $params = $this->request->param();

            $orderid = $this->request->param('orderid', 0, 'trim');
            $addrid = $this->request->param('addrid', 0, 'trim');
            

            //判断退货订单是否存在
            $order = model('Order.Order')->find($orderid);

            if(!$order)
            {
                $this->error('退货的订单不存在');
                exit;
            }

            //判断选择的收货地址是否存在
            $busid = isset($order['busid']) ? trim($order['busid']) : 0;
            $address = model('Business.Address')->where(['busid' => $busid, 'id' => $addrid])->find();

            if(!$address)
            {
                $this->error('退货的订单地址不存在');
                exit;
            }

            //判断订单商品是否存在
            $OrderProduct = model('Order.Product')->where(['orderid' => $order['id']])->select();

            if(!$OrderProduct)
            {
                $this->error(__('订单商品不存在'));
                exit;
            }

            // 开启事务
            $this->model->startTrans();
            $this->BackProductModel->startTrans();
            
            // 封装退货单数据
            $BackData = [
                'code' => build_code('BK'),
                'busid' => $order['busid'],
                'ordercode' => $order['code'],
                'remark' => $params['remark'],
                'expressid' => $params['expressid'],
                'expresscode' => $params['expresscode'],
                'amount' => $order['amount'],
                'status' => '0',
                'adminid' => $this->auth->id,
                'contact' => $address['consignee'],
                'phone' => $address['mobile'],
                'address' => $address['address'],
                'province' => $address['province'],
                'city' => $address['city'],
                'district' => $address['district'],
            ];

            $BackStatus = $this->model->validate('common/Depot/Back/Back')->save($BackData);

            if($BackStatus === FALSE)
            {
                $this->error(__($this->model->getError()));
                exit;
            }

            // 封装退货商品
            $BackProductData = [];

            foreach($OrderProduct as $item)
            {
                $BackProductData[] = [
                    'backid' => $this->model->id,
                    'proid' => $item['proid'],
                    'nums' => $item['pronum'],
                    'price' => $item['price'],
                    'total' => $item['total']
                ];
            }

            $BackProductStatus = $this->BackProductModel->validate('common/Depot/Back/Product')->saveAll($BackProductData);

            if($BackProductStatus === FALSE)
            {
                $this->model->rollback();
                $this->error($this->BackProductModel->getError());
                exit;
            }
            
            if($BackProductStatus === FALSE || $BackStatus === FALSE)
            {
                $this->BackProductModel->rollback();
                $this->model->rollback();
                $this->error("添加失败");
                exit;
            }else
            {
                $this->model->commit();
                $this->BackProductModel->commit();
                $this->success();
                exit;
            }
        }

        $this->view->assign('express', build_select('expressid', model("Express")->column('id,name'),[], ['class' => 'form-control selectpicker']));

        return $this->view->fetch();
    }

    // 编辑退货
    public function edit($ids = null)
    {
        $back = $this->model->find($ids);

        if(!$back)
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $product = $this->BackProductModel->with(['products'])->where(['backid' => $back['id']])->select();

        if(!$product)
        {
            $this->error('无退货商品');
            exit;
        }
        
        if($this->request->isPost())
        {
            $params = $this->request->param();
            
            $params['id'] = $ids;

            $result = $this->model->isUpdate(true)->save($params);

            if($result === FALSE)
            {
                $this->error($this->model->getError());
                exit;
            }else
            {
                $this->success();
                exit;
            }
        }

        $this->view->assign('back', $back);
        $this->view->assign('product', $product);
        $this->view->assign('express', build_select('expressid', model("Express")->column('id,name'), $back['expressid'], ['class' => 'form-control selectpicker']));

        return $this->view->fetch();
    }

    // 软删除
    public function del($ids = null)
    {
        $row = $this->model->select($ids);

        if(!$row)
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $result = $this->model->destroy($ids);

        if ($result === FALSE)
        {
            $this->error($this->model->getError());
            exit;
        }else
        {
            $this->success();
            exit;
        }
    }

    // 回收站
    public function recyclebin()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax())
        {
            if ($this->request->request('keyField')) 
            {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->onlyTrashed()
                ->with(['business'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();

            $list = $this->model
                ->onlyTrashed()
                ->with(['business'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    // 还原数据
    public function restore($ids = NULL)
    {
        //根据id判断数据是否存在
        $rows = $this->model->withTrashed()->whereIn('id', $ids)->select();
        
        if(!$rows)
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $result = $this->model->restore(['id'=>['in', $ids]]);

        if($result === FALSE)
        {
            $this->error('恢复数据失败');
            exit;
        }else
        {
            $this->success('恢复数据成功');
            exit;
        }
    }

    // 真实删除
    public function destroy($ids = null)
    {
        $row = $this->model->onlyTrashed()->select($ids);

        if (!$row)
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $result = $this->model->destroy($ids, true);

        if($result === false)
        {
            $this->error($this->model->getError());
            exit;
        }else
        {
            $thumbs = array_column($row, "thumbs");
            $thumbs = array_filter($thumbs);
            $thumbs = array_unique($thumbs);

            if(!empty($thumbs))
            {
                foreach($thumbs as $item)
                {
                    $item = ltrim($item,'/');
                    @is_file($item) && @unlink($item);
                }
            }
            
            $this->success();
            exit;
        }
    }

    // 退货单详情
    public function info($ids = null)
    {
        $row = $this->model->withTrashed()->with(['business'])->find($ids);

        if(!$row)
        {
            $this->error(__('退货单不存在'));
            exit;
        }

        $BackProductList = $this->BackProductModel->with(['products'])->where(['backid' => $ids])->select();

        $this->view->assign([
            'row' => $row,
            'BackProductList' => $BackProductList
        ]);

        return $this->view->fetch();
    }

    // 审核通过
    public function agree($ids = null)
    {
        $row = $this->model->select($ids);

        if (!$row) 
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $data = [
            'status' => '1',
            'reviewerid' => $this->auth->id
        ];

        $result = $this->model->where(['id' => ['in', $ids]])->update($data);
        
        if($result === FALSE)
        {
            $this->error('审核失败');
            exit;
        }else
        {
            $this->success();
            exit;
        }
    }

    // 拒绝审核
    public function reject($ids = null)
    {
        $row = $this->model->select($ids);

        if (!$row) 
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $data = [
            'status' => '-1',
            'reviewerid' => $this->auth->id
        ];

        $result = $this->model->where(['id' => ['in', $ids]])->update($data);
        
        if($result === FALSE)
        {
            $this->error('审核失败');
            exit;
        }else
        {
            $this->success();
            exit;
        }
    }
    
    // 撤回审核
    public function revoke($ids = null)
    {
        $row = $this->model->select($ids);

        if (!$row) 
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $data = [
            'status' => '0',
            'reviewerid' => NULL
        ];

        $result = $this->model->where(['id' => ['in', $ids]])->update($data);
        
        if($result === FALSE)
        {
            $this->error('撤回失败');
            exit;
        }else
        {
            $this->success();
            exit;
        }
    }

    // 确认收货入库
    public function receipt($ids = NULL)
    {
        //更新用户余额 -> 更新订单状态 -> 添加入库记录 -> 更新退货单状态，入库外键
        $row = $this->model->find($ids);

        if(!$row)
        {
            $this->error(__('退货单不存在'));
            exit;
        }

        $BackProductList = $this->BackProductModel->where(['backid' => $ids])->select();

        if(!$BackProductList)
        {
            $this->error(__('退货商品不存在'));
            exit;
        }

        // 实例化模型
        $OrderModel = model('Order.Order');
        $BusinessModel = model('Business.Business');
        $StorageModel = model('Depot.Storage.Storage');
        $StorageProductModel = model('Depot.Storage.Product');

        // 查询订单
        $order = $OrderModel->where(['code' => $row['ordercode']])->find();

        if(!$order)
        {
            $this->error('商品订单不存在');
            exit;
        }

        $business = $BusinessModel->find($order['busid']);

        if(!$business)
        {
            $this->error('用户不存在');
            exit;
        }

        // 开启事务
        $this->model->startTrans();
        $BusinessModel->startTrans();
        $OrderModel->startTrans();
        $StorageModel->startTrans();
        $StorageProductModel->startTrans();

        // 更新用户的余额
        $BusinessData = [
            'id' => $business['id'],
            'money' => bcadd($order['amount'],$business['money'],2)
        ];

        $BusinessStatus = $BusinessModel->isUpdate(true)->save($BusinessData);

        if($BusinessStatus === false)
        {
            $this->error('更新用户余额失败');
            exit;
        }

        // 更新订单的状态
        $OrderData = [
            'id' => $ids,
            'status' => -4,
        ];

        $OrderStatus = $OrderModel->isUpdate(true)->save($OrderData);

        if($OrderStatus === false)
        {
            $BusinessModel->rollback();
            $this->error('更新订单状态失败');
        }

        // 生成入库记录
        $StorageData =[
            'code' => build_code('ST'),
            'type' => 2,
            'amount' => $row['amount'],
            'status' => 0
        ];

        $StorageStatus = $StorageModel->save($StorageData);

        if($StorageStatus === FALSE)
        {
            $BusinessModel->rollback();
            $OrderModel->rollback();
            $this->error($StorageModel->getError());
            exit;
        }

        // 存放封装好的商品数据
        $ProductData = [];

        foreach($BackProductList as $item)
        {
            $ProductData[] = [
                'storageid' => $StorageModel->id,
                'proid' => $item['proid'],
                'nums' => $item['nums'],
                'price' => $item['price'],
                'total' => $item['total'],
            ];
        }

        // 验证数据
        $ProductStatus = $StorageProductModel->validate('common/Depot/Storage/Product')->saveAll($ProductData);

        if($ProductStatus === FALSE)
        {
            $StorageModel->rollback();
            $OrderModel->rollback();
            $BusinessModel->rollback();
            $this->error($StorageProductModel->getError());
            exit;
        }

        // 更新退货单状态与入库外键
        $BackData = [
            'id' => $row['id'],
            'status' => '2',
            'stromanid' => $this->auth->id,
            'storageid' => $StorageModel->id
        ];

        $BackStatus = $this->model->isUpdate(true)->save($BackData);

        if($BackStatus === FALSE)
        {
            $StorageProductModel->rollback();
            $StorageModel->rollback();
            $OrderModel->rollback();
            $BusinessModel->rollback();
            $this->error('修改收货状态失败');
            exit;
        }


        if($BusinessStatus === false || $OrderStatus === false || $StorageStatus === false || $ProductStatus === false || $BackStatus === false)
        {
            $this->model->rollback();
            $StorageProductModel->rollback();
            $StorageModel->rollback();
            $OrderModel->rollback();
            $BusinessModel->rollback();
            $this->error('确认收货入库失败');
            exit;
        }else
        {
            $BusinessModel->commit();
            $OrderModel->commit();
            $StorageModel->commit();
            $StorageProductModel->commit();
            $this->model->commit();
            $this->success('确认收货入库成功');
            exit;
        }
    }
}